package com.ayou.healthmanagement.service.impl;

import com.ayou.healthmanagement.pojo.HealthArchives;
import com.ayou.healthmanagement.pojo.HealthUser;
import com.ayou.healthmanagement.utils.JwtUtils;
import com.ayou.healthmanagement.utils.Result;
import com.ayou.healthmanagement.mapper.HealthArchivesMapper;
import com.ayou.healthmanagement.mapper.HealthUserMapper;
import com.ayou.healthmanagement.service.InitDataService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

@Service
public class InitDataServiceImpl implements InitDataService {

    @Data
    public class Illness{
        private Integer value;
        private String name;

        public Illness(Integer value, String name) {
            this.value = value;
            this.name = name;
        }
    }

    @Autowired
    private HealthUserMapper healthUserMapper;

    @Autowired
    private HealthArchivesMapper healthArchivesMapper;

    @Override
    public Result getInitAverageValue(HttpServletRequest request) {
        String token = request.getHeader("token");
        Integer id = Integer.parseInt(JwtUtils.getId(token));
        System.out.println("用户id =》"+id);
        HealthUser healthUser = healthUserMapper.selectById(id);
        HealthArchives archives = healthArchivesMapper.selectOne(new QueryWrapper<HealthArchives>().eq("user_id", healthUser.getId()));
        if (archives!=null && !healthUser.getUserRole().equals("A")){
            ArrayList<Double> list = new ArrayList<>();
            list.add(archives.getAge().doubleValue());
            list.add(archives.getHeight().doubleValue());
            list.add(archives.getWeight().doubleValue());
            list.add(Double.parseDouble(archives.getBloodPressure()));
            list.add(Double.parseDouble(archives.getBloodSugar()));
            list.add(Double.parseDouble(archives.getHeartRate()));
            return Result.success(list);
        }
        double ageAverageValue = healthArchivesMapper.getAgeAverageValue();
        double heightAverageValue = healthArchivesMapper.getHeightAverageValue();
        double weightAverageValue = healthArchivesMapper.getWeightAverageValue();
        double bloodPressureAverageValue = healthArchivesMapper.getBloodPressureAverageValue();
        double bloodSugarAverageValue = healthArchivesMapper.getBloodSugarAverageValue();
        double heartRateAverageValue = healthArchivesMapper.getHeartRateAverageValue()+1;
        ArrayList<Double> list = new ArrayList<>();
        list.add(ageAverageValue);
        list.add(heightAverageValue);
        list.add(weightAverageValue);
        list.add(bloodPressureAverageValue);
        list.add(bloodSugarAverageValue);
        list.add(heartRateAverageValue);
        System.out.println(ageAverageValue);
        return Result.success(list);
    }

    @Override
    public Result getIllness() {
        ArrayList<Illness> illnesses = new ArrayList<>();
        List<HealthArchives> healthArchives = healthArchivesMapper.selectList(new QueryWrapper<>());
        int a1 = 0, a2 = 0, a3 = 0; // 健康、亚健康、危险

        for (HealthArchives healthArchive : healthArchives) {
            // 1. 血压检测（空值安全处理）
            try {
                int bloodPressure = Integer.parseInt(healthArchive.getBloodPressure());
                if (bloodPressure > 140 || bloodPressure > 90) { // 逻辑需确认：收缩压>140 或 舒张压>90？
                    a3++;
                } else {
                    a1++;
                }
            } catch (NumberFormatException e) {
                // 记录日志或跳过无效数据
                continue;
            }

            // 2. 血糖检测（示例：空腹血糖正常值3.9-6.1mmol/L）
            try {
                float bloodSugar = Float.parseFloat(healthArchive.getBloodSugar());
                if (bloodSugar >= 4 && bloodSugar <= 6) {
                    a1++;
                } else {
                    a2++;
                }
            } catch (NumberFormatException e) {
                continue;
            }

            // 3. 心率检测
            try {
                int heartRate = Integer.parseInt(healthArchive.getHeartRate());
                if (heartRate >= 60 && heartRate <= 100) {
                    a1++;
                } else if (heartRate <= 150) {
                    a2++;
                } else {
                    a3++;
                }
            } catch (NumberFormatException e) {
                continue;
            }

            // 4. 体重检测（单位：kg）
            try {
                float weight = Float.parseFloat(String.valueOf(healthArchive.getWeight()));
                if (weight > 50 && weight < 200) {
                    a1++;
                } else {
                    a2++;
                }
            } catch (NumberFormatException e) {
                continue;
            }
        }

        // 返回统计结果（根据实际需求调整）
        illnesses.add(new Illness(a1, "健康"));
        illnesses.add(new Illness(a2, "亚健康"));
        illnesses.add(new Illness(a3, "危险"));
        return Result.success(illnesses);
    }

    @Override
    public Result getInitByArchiveNumber(String archiveNumber) {
        HashMap<String, Object> map = new HashMap<>();
        HealthArchives healthArchives = healthArchivesMapper.selectOne(new QueryWrapper<HealthArchives>().eq("archive_number", archiveNumber));
        ArrayList<Integer> list = new ArrayList<>();
        list.add(healthArchives.getAge()*100);//年龄
        list.add(healthArchives.getWeight()*100);//体重
        list.add(healthArchives.getHeight()*100);//身高
        list.add(Integer.parseInt(healthArchives.getHeartRate())*100);//心率
        list.add(Integer.parseInt(healthArchives.getBloodSugar())*100);//血糖
        list.add(Integer.parseInt(healthArchives.getBloodPressure())*100);//血压
        ArrayList<Integer> list1 = new ArrayList<>();
        Random random = new Random();
        list1.add(random.nextInt(3000) + 1000);
        list1.add(random.nextInt(3000) + 1000);
        list1.add(random.nextInt(3000) + 1000);
        list1.add(random.nextInt(3000) + 1000);
        list1.add(random.nextInt(3000) + 1000);
        list1.add(random.nextInt(3000) + 1000);
        map.put("list1",list);
        map.put("list2",list1);
        map.put("healthArchives",healthArchives);
        return Result.success(map);
    }
}
